import LoginPage from '@/views/loginPage.vue'
import AccountManagement from '@/views/main/account/AccountManagement.vue'
import EmailService from '@/views/main/base-info/EmailService.vue'
import TeacherStats from '@/views/main/reports/TeacherStats.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import MainPage from '@/views/main/MainPage.vue'
import { ElMessage } from 'element-plus'
import TheHome from '@/views/main/home/TheHome.vue'
import ProjectBase from '@/views/main/base-info/ProjectBase.vue'
import TrainingProgram from '@/views/main/project/TrainingProgram.vue'
import ProjectStats from '@/views/main/reports/ProjectStats.vue'
import { getUserRole } from '@/utils/token'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path:'/',
      redirect:'/main'
    },
    {
      path:'/login',
      component:LoginPage
    },
    {
      path:'/main',
      component:MainPage,
      redirect:'/main/home',
      children:[
        {
          path:'home',
          component:TheHome
        },
        {
          path:'accounts',
          component:AccountManagement
        },
        {
          path:'emails-service',
          component:EmailService
        },
        {
          path:'project-base',
          component:ProjectBase
        },
        {
          path:'training-program',
          component:TrainingProgram
        },
        {
          path:'project-stats',
          component:ProjectStats
        },
        {
          path:'teacher-stats',
          component:TeacherStats
        }
      ]
    }
  ],
})

const whiteList = ['/login']
const adminPath = ['/main/accounts','/main/emails-service','/main/project-base','/main/training-program','/main/project-stats']

router.beforeEach((to) => {
  const useStore = useUserStore()
  const {token} = useStore
  if (token) {
    console.log(to.path,adminPath.includes(to.path),getUserRole());

    if(to.path === '/login') {
      return '/'
    } if (adminPath.includes(to.path) && getUserRole() == 2) {
      ElMessage.error('您没有访问权限')
      return false
    } else {
      return true
    }
  }else {
    if(whiteList.includes(to.path)) {
      return true
    }else {
      ElMessage.error("您还未登录,请先登录")
      return '/login'
    }
  }
} )
export default router
